﻿/**
* @description  Blurs an image in or out during the transition.
*/
package com.foed.animation.transitions {

	import flash.display.DisplayObject;
	import flash.filters.BlurFilter;
	
	public class BlurTransition extends Transition {
		
		private static const DEFAULT_BLUR:Number = 25;
		private var _quality:int = 1;
		private var _blurFilter:BlurFilter;
	
		/**
		* @description  Constructor.
		*
		* @param  pClip  The clip on which to perform the transition.
		* @param  pStartTransform  The starting values for the color transition.
		* @param  pEndTransform  The destination values for the color transition.
		* @param  pTime  The length in milliseconds for the transition.
		* @param  pType  The type of transition. IN moves from startTransform to endTransfom. OUT does the opposite.
		* @param  pEaseFunction  The function to use to transform the transition values over time.
		*/
		public function BlurTransition(
			pClip:DisplayObject=null,
			pStartTransform:Object=null,
			pEndTransform:Object=null,
			pTime:Number=1000,
			pType:String=null,
			pEaseFunction:Function=null
		) {
			pStartTransform = (pStartTransform == null ?  {blurX:25,blurY:25} : pStartTransform) ;
			pEndTransform = (pEndTransform == null ?  {blurX:0,blurY:0} : pEndTransform) ;
			super(pClip, pTime, pStartTransform, pEndTransform, pType, pEaseFunction);
		}
	
		/**
		* @description  Called each iteration of the tween by the TweenRunner to transform values.
		*
		* @param  pChangeValues  The current values of the transition at each iteration of the tween.
		*/
		override protected function runTransition(pChangeValues:Object):void {
			if (_blurFilter != null) {
				_blurFilter.blurX = pChangeValues.blurX;
				_blurFilter.blurY = pChangeValues.blurY;
				var pFilters:Array = clip.filters.slice(0, -1);
				clip.filters = pFilters.concat(_blurFilter);
			}
			super.runTransition(pChangeValues);
		}

		/**
		* @description  Returns the clip's filters array ensuring that any final blur is removed.
		*
		* @returns  The filters array for the managed clip without a BlurFilter as the final filter.
		*/
		private function getFiltersWithoutBlur():Array {
			var pFilters:Array = clip.filters || [];
			if (pFilters[pFilters.length-1] is BlurFilter) pFilters = pFilters.slice(0, -1);
			return pFilters;
		}
	
		/**
		* @description  Prepares clip to have transitions applied by adding new parent clip.
		*/
		override protected function prepare():void {
			super.prepare();
			var pFilters:Array = getFiltersWithoutBlur();
			_blurFilter = new BlurFilter(0, 0, _quality);
			pFilters.push(_blurFilter);
			clip.filters = pFilters;
		}
	
		/**
		* @description  Removes any artifacts of the transition.
		*/
		override protected function cleanUp():void {
			super.cleanUp();
			var pFilters:Array = getFiltersWithoutBlur();
			clip.filters = pFilters;
			_blurFilter = null;
		}

	}
	
}